﻿using Net_SCADA.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Net_SCADA
{
    public partial class Form_Design : fdBaseForm
    {

        private bool isFormLoading=true;
        List<TextBox> infoEdit=new List<TextBox>();
        List<TextBox> proEdit=new List<TextBox>();
        Dictionary<string,TextBox> EditBox=new Dictionary<string, TextBox>();//使用zoneID来绑定infoedit的textbox
        String EditProductVersion ="";
        String SelectedProductVersion="";
        public bool isNewProduct=false;
        int designCols=10;

        public List<Label> lstlbl = new List<Label>();
        private Dictionary<string, string[]> gridTitle = new Dictionary<string, string[]>();

        private Font[] groupTitleFont = new Font[] { new Font("Microsoft YaHei", 12f), new Font("Arial", 12f) };
        private Font[] itemTitleFont = new Font[] { new Font("Microsoft YaHei", 9f), new Font("Arial", 9f) };
        private Font[] productTitleFont = new Font[] { new Font("Microsoft YaHei", 9f), new Font("Arial", 9f) };
        private Font[] editBoxFont = new Font[] { new Font("Microsoft YaHei", 15f), new Font("Arial", 15f) };
        private Font[] gridTitleFont = new Font[] { new Font("Microsoft YaHei", 12f), new Font("Arial", 12f)};

        public Form_Design()
        {
            InitializeComponent();
        }

        private void Form_Design_Load(object sender , EventArgs e)
        {
            formLanguageIndex = -1;
            isFormLoading = true;
            netForms.SetPostionAndSize(this);
            LoadInterface();
            SetProductInfoGrid();
            LoadProgramEditInterface();
            LoadProductInfos();
            isFormLoading = false;
        }

        private void LoadInterface()
        {
            grdProduct.Location = new Point(2 , grdProduct.Top);
            grdProduct.Size = new Size(this.Width - 6 - netForms.fmTop.btnWidth , 213);
            btn_SaveProduct.Size= btn_NewProduct.Size= btn_DeleteProduct.Size =  new Size(netForms.fmTop.btnWidth,45);
            btn_SaveProduct.Font = btn_DeleteProduct.Font = btn_NewProduct.Font= fdPublicFunction.Getfont(btn_SaveProduct.Height / 3 , "Arial", FontStyle.Regular);
            btn_SaveProduct.Location = new Point(this.Width - btn_SaveProduct.Width - 2 , grdProduct.Top+ grdProduct.Height - btn_SaveProduct.Height );
            btn_DeleteProduct.Location = new Point(this.Width - btn_DeleteProduct.Width - 2 , btn_SaveProduct.Top - btn_DeleteProduct.Height - 2);
            btn_NewProduct.Location = new Point(this.Width - btn_NewProduct.Width - 2 , btn_DeleteProduct.Top - btn_NewProduct.Height - 2);
           // btn_AlarmSelection.Location=new Point(this.Width - btn_AlarmSelection.Width - 2 , btn_NewProduct.Top - btn_AlarmSelection.Height - 2);
            lbl_Search.Location = new Point(btn_SaveProduct.Left , grdProduct.Top);
            txt_SearchByName.Location = new Point(btn_SaveProduct.Left ,4);
            txt_SearchByName.Width = btn_SaveProduct.Width;
            lbl_Search.Location = new Point(txt_SearchByName.Left - 5 - lbl_Search.Width , txt_SearchByName.Top+3);
            lbl_ProgramTitle.Location = new Point(0 , grdProduct.Top + grdProduct.Height + 5);
            lbl_ProgramTitle.Width = this.Width;
            pnl_ProductEdit.Left = (this.Width - pnl_ProductEdit.Width) / 2;
        }
        private void LoadProgramEditInterface()
        {
            designCols = NetLine.DesignCols;
            string[] groupid=DBOperate.GetDesignGroupUsed();
            if (groupid == null || groupid.Length <= 0) return;
            DataTable dtGroup=DBOperate.GetDesignGroupSet();
            if (dtGroup == null || dtGroup.Rows.Count <= 0) return;
            Dictionary<string,Panel> groupPnl=new Dictionary<string, Panel>();
            Dictionary<string,int> zonesInPnl=new Dictionary<string, int>();
            int top=lbl_ProgramTitle.Top+lbl_ProgramTitle.Height +5;
            int w=(this.Width -designCols*5-5)/ designCols;
            int GroupRows=0;
            Panel pnl=null;
            DataTable dt=DBOperate.GetSetPointSet();
            if (dt == null || dt.Rows.Count == 0) return;
            for (int i = 0 ; i < groupid.Length ; i++)
            {
                zonesInPnl.Add(groupid[i] , 0);
                string s_str = string.Format("groupid='{0}'", groupid[i]);
                DataRow[] dr=dt.Select(s_str);
                GroupRows = (dr.Length - 1) / designCols + 1;
                groupPnl.Add(groupid[i], new Panel()
                {
                    Size = new Size(this.Width , 35 + 60 * GroupRows) ,
                    Location = new Point(0 , (i > 0 ? groupPnl[groupid[i - 1]].Height + groupPnl[groupid[i - 1]].Top + 10 : top)) ,
                });
                pnl = groupPnl[groupid[i]];
                string[] s = dtGroup.Select("groupid=" + groupid[i])[0]["groupname"].ToString().Split(';');
                Label l = new Label()
                {
                    Name=$"lblGroup{i}",
                    Text = s[MultipleLanguage.systemLanguageIndex],
                    Size = new Size(300, 22),
                    AutoSize = false,
                    BorderStyle = BorderStyle.FixedSingle,
                    Location = new Point(10, 1),
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Teal,
                    ForeColor = Color.White,
                    Font = groupTitleFont[MultipleLanguage.systemLanguageIndex],
                };
                MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                        l.Name,"Label","Text",s,"",groupTitleFont
                    ));

                pnl.Controls.Add(l);
                lstlbl.Add(l);
                pnl.Controls.Add(new Label()
                {
                    AutoSize = false ,
                    Size = new Size(this.Width , 2) ,
                    BackColor = Color.Gray ,
                    Location = new Point(0 , 6)
                });
                this.Controls.Add(pnl);
            }
            Label lbl;
            string gID="";
            for (int i = 0 ; i < NetLine.setpoint.Count ; i++)
            {
                gID = NetLine.setpoint[i].GroupID.ToString();
                lbl = new Label()
                {
                    Name=$"lblItem{i}",
                    Text = NetLine.setpoint[i].ZoneName[MultipleLanguage.systemLanguageIndex] + " " + NetLine.setpoint[i].Unit,
                    AutoSize = false ,
                    Location = new Point(5 + (zonesInPnl[gID] % designCols) * (w + 5) , 32 + 60 * (zonesInPnl[gID] / designCols)) ,
                    Size = new Size(w , 30) ,
                    Font = itemTitleFont[MultipleLanguage.systemLanguageIndex],
                    TextAlign=ContentAlignment.BottomLeft
                };
                MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                    lbl.Name, "Label", "Text", NetLine.setpoint[i].ZoneName, NetLine.setpoint[i].Unit, itemTitleFont
                ));
                lstlbl.Add(lbl);
                groupPnl[gID].Controls.Add(lbl);
                proEdit.Add(new TextBox()
                {
                    Location = new Point(lbl.Left , lbl.Top + lbl.Height) ,
                    Tag = NetLine.setpoint[i] ,
                    BackColor = Color.PaleTurquoise ,
                    ForeColor = Color.FromArgb(64 , 64 , 64) ,
                    Size = new Size(w , 30) ,
                    Font = editBoxFont[MultipleLanguage.systemLanguageIndex],
                    TextAlign = HorizontalAlignment.Center,
                    Text="0",
                });
                proEdit.Last().KeyPress += proEdit_KeyPress; ;
                proEdit.Last().LostFocus += proEdit_LostFocus; ;
                groupPnl[gID].Controls.Add(proEdit.Last());
                EditBox.Add(NetLine.setpoint[i].ZoneID.ToString() , proEdit.Last());
                zonesInPnl[gID]++;
            }
        }

        private void proEdit_LostFocus(object sender , EventArgs e)
        {
            TextBox txt= sender as TextBox;
            SetPoint sp=txt.Tag as SetPoint;
            txt.Text = txt.Text.Trim();
            if (txt.Text == "")
            {
                txt.Text = "0";
                return;
            }
            if (Convert.ToSingle(txt.Text) > sp.sv.Max)
            {
                txt.Text = sp.sv.Max.ToString();
                return;
            }
            if (Convert.ToSingle(txt.Text) < sp.sv.Min)
            {
                txt.Text = sp.sv.Min.ToString();
                return;
            }
            if (sp.sv.DataType.ToUpper() == "TIME")//判断时间输入格式
            {
                int i=txt.Text.IndexOf(".");
                if ( i>= 0)
                {
                    string s=txt.Text.Substring(i+1);
                    if (s.Length > 2) s = s.Substring(0 , 2);
                    if (Convert.ToInt32(s) > 59)
                        txt.Text = txt.Text.Substring(0 , i) + ".59";
                    else
                        txt.Text = txt.Text.Substring(0 , i) + "."+s;
                }
            }
        }

        private void proEdit_KeyPress(object sender , KeyPressEventArgs e)
        {
            TextBox txt= sender as TextBox;
            SetPoint sp=txt.Tag as SetPoint;
            int dp=sp.sv.DP + (sp.sv.DataType.ToUpper() == "TIME" ? 1 : 0);
            e.Handled= fdPublicFunction.CheckInput(dp , txt.Text , e);
        }
        private void SetProductInfoGrid()
        {
            DataTable dt=DBOperate.GetProductInfoTitle();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    gridTitle[$"info{dt.Rows[i]["infoid"]}"] = dt.Rows[i]["infotitle"].ToString().Split(';');
                    grdProduct.Columns.Add(gridTitle.Last().Key, gridTitle.Last().Value[MultipleLanguage.systemLanguageIndex]);

                    MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                        "grdProduct", "DataGridView", gridTitle.Last().Key, gridTitle[$"info{dt.Rows[i]["infoid"]}"], "", gridTitleFont
                    ));

                    Label lbl = new Label()
                    {
                        Name = $"lblProductTitle{i}",
                        AutoSize = false,
                        Text = gridTitle.Last().Value[MultipleLanguage.systemLanguageIndex],
                        Size = new Size(120, 23),
                        Location = new Point(2, 45 + i * 30),
                        Font = productTitleFont[MultipleLanguage.systemLanguageIndex],
                        TextAlign = ContentAlignment.MiddleRight,
                        Tag = gridTitle.Last().Value
                    };
                    lstlbl.Add(lbl);
                    MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                        lbl.Name,"Label","Text", gridTitle.Last().Value,"", productTitleFont
                        ));
                    pnl_ProductEdit.Controls.Add(lbl);
                    infoEdit.Add(new TextBox() {
                        Size = new Size(300 , 23) ,
                        Location=new Point(lbl.Left+lbl.Width +2,lbl.Top-1),
                        Tag= "info" + dt.Rows[i]["infoid"].ToString(),
                        Font =lbl.Font
                    });
                    pnl_ProductEdit.Controls.Add(infoEdit.Last());
                }
                grdProduct.Columns.Add("ProductVersion" , "ProductVersion");
                grdProduct.Columns["ProductVersion"].Visible = false;
                grdProduct.Columns.Add("keyalarm" , "alarm");
                grdProduct.Columns["keyalarm"].Visible = false;
                grdProduct.Columns.Add("lampalarm" , "alarm");
                grdProduct.Columns["lampalarm"].Visible = false;
                pnl_ProductEdit.Height = infoEdit.Last().Top + infoEdit.Last().Height + 5;
                btn_ProductEditConfirm.Top = pnl_ProductEdit.Height - 5 - btn_ProductEditConfirm.Height;
                btn_ProductEditCancel.Top = btn_ProductEditConfirm.Top - 5 - btn_ProductEditConfirm.Height;
            }
        }
        public void LoadProductInfos()
        {
            isFormLoading = true;
            DataTable dt = DBOperate.GetProductInfo();
            grdProduct.Rows.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                grdProduct.Rows.Add(dt.Rows.Count);
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    for (int j = 0 ; j < grdProduct.Columns.Count ; j++)
                    {
                        grdProduct.Rows[i].Cells[j].Value = dt.Rows[i][grdProduct.Columns[j].Name];
                    }
                }
                grdProduct.Rows[0].Selected=true;
                SelectedProductVersion= grdProduct.Rows[0].Cells["ProductVersion"].Value.ToString();
                lblSubTitle.Text = SelectedProductVersion;
                lblSubTitle.Left = (int)(fdPublicFunction.GetTextSize(lbl_ProductTitle.Font, lbl_ProductTitle.Text).Width * 1.1f);
                LoadProductProgram();
            }
            isFormLoading = false;
        }
        private void showOneProduct(string version="")
        {
            lbl_Version.Text = EditProductVersion;
            if (version=="")
            {
                foreach (TextBox item in infoEdit)
                    item.Text = "";
                return;
            }
            foreach (TextBox item in infoEdit)
            {
                item.Text = grdProduct.SelectedRows[0].Cells[item.Tag.ToString()].Value.ToString();
            }
        }
        private bool SaveProductProgram()//需要version和数据的内容,用SVID做字段名，在获取数据时使用editbox字典组织数据
        {
            Dictionary<string,string> v=new Dictionary<string, string>();
            SetPoint sp=null;
            for (int i = 0 ; i < proEdit.Count ; i++)
            {
                sp = proEdit[i].Tag as SetPoint;
                v.Add(sp.ZoneID.ToString() , proEdit[i].Text);
            }
           return  DBOperate.SaveProductProgram(SelectedProductVersion , v);
        }
        private void LoadProductProgram()//使用version，从数据库中读取数据，并展示在infoEdit中，通过SVID来设置infoedit的数据
        {
            DataTable dt= DBOperate.GetProductProgram(SelectedProductVersion);
            if (dt == null || dt.Rows.Count == 0) {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[6], "", formLanguageIndex);
                //fdMessage.ShowMsg("当前产品还没有设置工艺参数，请先设置工艺参数再保存！" , "工艺编辑" , 1 , 0);
                foreach (TextBox item in proEdit)
                    item.Text = "0";
                return;
            } 
            DataRow dr= dt.Rows[0];
            for (int i = 0 ; i < NetLine.setpoint.Count ; i++)
            {
                EditBox[NetLine.setpoint[i].ZoneID.ToString()].Text = dr[NetLine.setpoint[i].ZoneID.ToString()].ToString();
            }
        }
        private void btn_SaveProduct_Click(object sender , EventArgs e)
        {
            if(SelectedProductVersion=="")
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[7], "", formLanguageIndex);
               // fdMessage.ShowMsg("请先加入产品，再进行工艺保存" ,"工艺编辑" , 1 , 0);
                return;
            }
            if(SaveProductProgram())
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[8], "", formLanguageIndex);
                //fdMessage.ShowMsg("工艺保存成功！" , "工艺编辑" , 1 , 0);
            else
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[9], "", formLanguageIndex);
               // fdMessage.ShowMsg("工艺保存失败！请检查数据库" , "工艺编辑" , 1 , 0);

        }
        private void btn_NewProduct_Click(object sender , EventArgs e)
        {
            isNewProduct = true;
            pnl_ProductEdit.Visible = true;
            EditProductVersion = DateTime.Now.ToString("yyyyMMddHHmmss");
            showOneProduct();
        }
        private void btn_ProductEditCancel_Click(object sender , EventArgs e)
        {
            isNewProduct = false;
            pnl_ProductEdit.Visible = false;
            grdProduct.Enabled = true;
        }
        private void btn_ProductEditConfirm_Click(object sender , EventArgs e)
        {
            pnl_ProductEdit.Visible = false;
            Dictionary<string,string> infos=new Dictionary<string, string>();
            foreach (TextBox item in infoEdit)
                infos.Add(item.Tag.ToString() , item.Text);
            infos.Add("ProductVersion" , EditProductVersion);
            infos.Add("isUsable" , "1");
            if (isNewProduct)
                DBOperate.SaveProductInfo(infos);
            else
                DBOperate.ModifyProductInfo(infos);
            grdProduct.Enabled = true;
            LoadProductInfos();
        }
        private void grdProduct_CellDoubleClick(object sender , DataGridViewCellEventArgs e)
        {
            isNewProduct = false;
            pnl_ProductEdit.Visible = true;
            SelectedProductVersion=EditProductVersion = grdProduct.SelectedRows[0].Cells["ProductVersion"].Value.ToString();
            showOneProduct(EditProductVersion);
            grdProduct.Enabled = false;
        }

        private void grdProduct_SelectionChanged(object sender , EventArgs e)
        {
            if (isFormLoading) return;
            if (grdProduct.CurrentRow.Cells["ProductVersion"].Value == null)
            {
                SelectedProductVersion = "";
                return;
            }
            SelectedProductVersion = grdProduct.CurrentRow.Cells["ProductVersion"].Value.ToString();
            //lbl_ProductTitle.Text = "产品信息" + SelectedProductVersion;
            lblSubTitle.Text = SelectedProductVersion;
            lblSubTitle.Left = (int)(fdPublicFunction.GetTextSize(lbl_ProductTitle.Font, lbl_ProductTitle.Text).Width * 1.1f);

            LoadProductProgram();
        }

        private void btn_DeleteProduct_Click(object sender , EventArgs e)
        {
            fdMessage.ShowMsg(MultipleLanguage.messageInfos[12], grdProduct.CurrentRow.Cells["info0"].Value.ToString(), formLanguageIndex);
           // fdMessage.ShowMsg("确认删除产品名为:【" + grdProduct.CurrentRow.Cells["info0"].Value.ToString() + "】的相关信息吗？" , "删除工艺" , 2 , 2);
        }

        public void DeleteProductProgram()
        {
            if(DBOperate.DeleteProductInfo(grdProduct.CurrentRow.Cells["ProductVersion"].Value.ToString()))
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[10], "", formLanguageIndex);
                //fdMessage.ShowMsg("产品工艺删除成功！" , "删除工艺" , 1 , 0);
                LoadProductInfos();
            }
            else
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[11], "", formLanguageIndex);
                //fdMessage.ShowMsg("产品工艺删除失败，请确认数据库状态！" , "删除工艺" , 1 , 0);
            }
        }

        private void btn_AlarmSelection_Click(object sender , EventArgs e)
        {
            Form_AlarmSelection fm=new Form_AlarmSelection(
                grdProduct.CurrentRow.Cells["ProductVersion"].Value.ToString(),
                grdProduct.CurrentRow.Cells["info0"].Value.ToString(),
                grdProduct.CurrentRow.Cells["keyalarm"].Value.ToString(),
                grdProduct.CurrentRow.Cells["lampalarm"].Value.ToString()
                );
            fm.OnAlarmSelectionSaved += Fm_OnAlarmSelectionSaved;
            fm.ShowDialog();
        }

        private void Fm_OnAlarmSelectionSaved(bool isSaved , string productSerial , string KeyAlarmSelection , string LampAlarmSelection)
        {
            if (isSaved)
            {
                for (int i = 0 ; i < grdProduct.Rows.Count ; i++)
                {
                    if (grdProduct.Rows[i].Cells["ProductVersion"].Value.ToString() == productSerial)
                    {
                        grdProduct.Rows[i].Cells["keyalarm"].Value = KeyAlarmSelection;
                        grdProduct.Rows[i].Cells["lampalarm"].Value = LampAlarmSelection;
                        break;
                    }
                }
            }
        }

        private void Form_Design_Activated(object sender, EventArgs e)
        {
            if (formLanguageIndex != MultipleLanguage.systemLanguageIndex)
            {
                formLanguageIndex=MultipleLanguage.systemLanguageIndex;
                //foreach (Label lbl in lstlbl)
                //{
                //    if(lbl.Tag!=null)
                //    {
                //        string[] s=lbl.Tag as string[];
                //        lbl.Text = s[formLanguageIndex];
                //    }
                //}
            }
        }
    }
}
 